﻿using System;
using System.Web;
using System.Runtime.Caching;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Ruandao.HostServer
{
    using Ruandao.HostServer.SqlEntityAccess;
    using Ruandao.Misc;

    abstract public class Site
    {

        internal Site SetFromEntity(SiteEntity siteEntity)
        {
            TypeUtil.MapProperty(siteEntity, this,
                "SiteGuid",
                "SiteName",
                "Title",
                "Description",
                "OwnerGuid",
                "UserLevel",
                "CreateDate",
                "DatabaseId",
                "SiteDbName",
                "FileStorageId",
                "ContainsAccount");
            return this;
        }

        // 返回各个网站的所有域名字典，key是DomainType, value是DomainName。
        // 性能：根据DomainNames可以进一步从缓存中直接得到DomainObject。
        override public IDictionary<string, List<string>> GetDomains()
        {
            var dic = new Dictionary<string, List<string>>();
            ObjectCache cache = MemoryCache.Default;
            string cacheKey = "SITE_DOMAINS_" + this.SiteGuid.ToString();
            IDictionary<string, List<string>> domains = cache[cacheKey] as IDictionary<string, List<string>>;
            if (domains == null)
            {
                domains = new Dictionary<string, List<string>>();
                foreach (var e in DomainEntity.SearchEntities("WHERE SiteGuid='" + this.SiteGuid.ToString() + "'"))
                {
                    if (domains.ContainsKey(e.DomainType.ToLower()))
                    {
                        domains[e.DomainType.ToLower()].Add(e.DomainName);
                    }
                    else
                    {
                        List<string> list = new List<string>();
                        list.Add(e.DomainName);
                        domains.Add(e.DomainType.ToLower(), list);
                    }
                }
                CacheItemPolicy policy = new CacheItemPolicy();
                cache.Set(cacheKey, domains, policy);
            }
            return domains;

        }

    }

}
